import * as types from '../mutation-types'
import { updateCartInfo, updateCenterCartInfo, settlementInfo, settlementCenterInfo } from '@/service/getData'
import router from '@/router/index'

export default {
	state: {
		invalidItems: null
	},
	mutations: {
		updateInvalidItems(state, info) {
			state.invalidItems = info;
		}
	},
	actions: {
		// 小店购物车type: add：+1, minus: -1, del:删除, checked:选择, selAll:全选
		updateCart ({ commit, rootState }, { type, item } ) {
			commit('showMask', true)
			if(!item) return
			let resolve = () => {
				let params = JSON.stringify(
					{
						"app": "wap",
						"operationInfos": [
							{
								"itemNo": item.itemNo,
								"tickStatus": tickStatus,
								"requestQty": requestQty,
								"deleteFlag": deleteFlag //删除购物车
							}
						],
						"cartHeadInfo": {
							"mdmCityCode": rootState.position.cityCode,
							"storeLocation": rootState.position.storeLocation,
							"poiId": rootState.position.poiId,
      						"areaId": rootState.position.areaId
						},
						"appVersion": "3.2.2"
					}
				)

				updateCartInfo ( params )
					.then((products) => {
						commit('updateSufreshCarts', { products })
						//commit('showMask', false)
					});
			}

			let requestQty = item.cmmdtyQty, deleteFlag = 'N' , tickStatus = item.tickStatus

			if( type == 'minus'){
				if(item.cmmdtyQty == 1){
					AlertBox({
						type: 'doubleBtn',
						msg: '要删除该商品？',
						confirmText: '确定',
						cancelText: '取消',
						confirm: ()=>{
							deleteFlag = "Y"
							resolve()
						},
						cancel: ()=>{
							commit('showMask', false)
						}
					})
					return
					
				}else{
					let minQty = '';

					// 判断库存数是否小于购物车数量
					if(item.activityTypes==1&&parseInt(item.limitActivityInfo.limitQty)<=parseInt(item.inventoryQty)){
						minQty = item.limitActivityInfo.limitQty
					}else{
						minQty = item.inventoryQty
					}

					if(minQty<parseInt(item.cmmdtyQty)){
						requestQty = item.inventoryQty;
					}else{
						requestQty = parseInt(item.cmmdtyQty) - 1;
					}

					//requestQty = parseInt(item.cmmdtyQty) - 1;
				}
			}else if(type == 'del' ){

				deleteFlag = "Y"

			}else if(type == 'checked'){

				tickStatus = item.tickStatus=='1'? 0 : 1;

			}else{
				
				requestQty = parseInt(item.cmmdtyQty) + 1;
			}

			resolve();
		}

		// 小店购物车全选
		,selAllCart ({ commit, rootState }, {item} ) {
			commit('showMask', true)
			if(!item) return
			let products = [];
			let tickStatus = item.some(x => x.tickStatus==0 ) ?1:0
			item.forEach(item => {
				products.push(
					{
						"itemNo": item.itemNo,
						"tickStatus": tickStatus,
						"requestQty": item.requestQty,
						"deleteFlag": "N" //删除购物车
					}
				)
			})
			//debugger
			let params = JSON.stringify(
				{
					"app": "wap",
					"operationInfos": products,
					"cartHeadInfo": {
						"mdmCityCode": rootState.position.cityCode,
						"storeLocation": rootState.position.storeLocation,
						"poiId": rootState.position.poiId,
      					"areaId": rootState.position.areaId
					},
					"appVersion": "3.2.2"
				}
			)
			
			updateCartInfo ( params )
				.then((products) => {
					commit('updateSufreshCarts', { products })
					//commit('showMask', false)
				});
		}

		// 中心仓购物车type: add：+1 , minus: -1 , del:删除 ,checked 
		,updateCenterCart ({ commit, rootState }, { type, item } ) {
			commit('showMask', true)
			if(!item) return
			let resolve = () => {
				let params = JSON.stringify(
					{
						"cartHeadInfo": {
							"opType": "1",
							"operationStoreCode": rootState.position.storeLocation,
							"tempCartId": "",
							"userFlag": "0",
							"operationChannel": "50",
							"operationTerminal": "06",
							"operationEquipment": "06"
						},
						"operationInfos": [
							{
							"deleteFlag": deleteFlag,
							"itemNo": info.itemNo,
							"requestQty": requestQty,
							"tickStatus": tickStatus
							}
						]
					}
				)

				updateCenterCartInfo ( params )
					.then((products) => {
						
						// 判断当前商品是否有货
						/**
						 * 增加购物车时，如果数量大于库存会在接口errorInfos字段中提示
						 */
						let errList = products.data.errorInfos;
						let errIndex = errList.findIndex( x => x.itemNo==info.itemNo)
						if(errIndex>=0){
							let msg = errList[errIndex].errorMessage;
							errList.splice(errIndex,errIndex+1);
							var pro = products.data.cmmdtyInfos.filter(x=>x.cmmdtyHeadInfo.itemNo==info.itemNo)
							if(!pro.length){return}
							pro=pro[0]
							pro.cmmdtyHeadInfo.isOffline = true
							pro.cmmdtyHeadInfo.isOfflineMsg = msg
						}
						//debugger
						commit('updateCenterCarts', { products })
					});
			}

			var info = item.mainCmmdtyInfo.mainCmmdtyDetailInfo
			let requestQty = info.cmmdtyQty, deleteFlag = 'N' , tickStatus = info.tickStatus

			if( type == 'minus'){
				if(info.cmmdtyQty == 1){
					AlertBox({
						type: 'doubleBtn',
						msg: '要删除该商品？',
						confirmText: '确定',
						cancelText: '取消',
						confirm: () => {
							deleteFlag = "Y"
							resolve()
						},
						cancel: ()=>{
							commit('showMask', false)
						}
					})
					return
				}else{
					requestQty = parseInt(info.cmmdtyQty) - 1;
				}
			}else if(type == 'del' ){
				deleteFlag = "Y"
			}else if(type == 'checked'){
				tickStatus = info.tickStatus=='1'? 0 : 1;
			}else{
				requestQty = parseInt(info.cmmdtyQty) + 1;
			}
			resolve()

		}

		// 中心仓购物车全选
		/**
		 * type: shop, all
		 */
		,selAllCenterCart ({ commit, rootState }, {type, item} ) {
			commit('showMask', true)
			if(!item) return
			let products = [], tickStatus = '';
			if(type == 'all'){
				  tickStatus = Object.values(item).some(a=>Object.values(a.list).some(i=>i.some(x => x.mainCmmdtyInfo.mainCmmdtyDetailInfo.tickStatus==0 )))?1:0
				//tickStatus = Object.values(item).every(item => item.list.every(x=>x.mainCmmdtyInfo.mainCmmdtyDetailInfo.tickStatus=='1')) ?0:1
				Object.values(item).forEach(item => {
					Object.values(item.list).forEach(list => {
						list.forEach(item => {
							products.push(
								{
									"itemNo": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.itemNo,
									"tickStatus": tickStatus,
									"requestQty": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.requestQty,
									"deleteFlag": "N" 
								}
							)
						})
					})
				})
			}else{
				tickStatus = Object.values(item).some(i => i.some(x => x.mainCmmdtyInfo.mainCmmdtyDetailInfo.tickStatus==0 )) ?1:0
				Object.values(item).forEach(item => {
					item.forEach(item => {
						products.push(
							{
								"itemNo": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.itemNo,
								"tickStatus": tickStatus,
								"requestQty": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.requestQty,
								"deleteFlag": "N" 
							}
						)
					})
				})
				
			}
			
			//debugger
			let params = JSON.stringify(
				{
					"cartHeadInfo": {
						"opType": "1",
						"operationStoreCode": rootState.position.storeLocation,
						"tempCartId": "",
						"userFlag": "0",
						"operationChannel": "50",
						"operationTerminal": "06",
						"operationEquipment": "06"
					},
					"operationInfos": products
				}
			)
			
			updateCenterCartInfo ( params )
				.then((products) => {
					commit('updateCenterCarts', { products })
				});
		}

		// 清空无效商品
		,delNosale({ commit, rootState }, item ) {
			commit('showMask', true)
			AlertBox({
				type: 'doubleBtn',
				msg: '失效商品清空后将无法恢复，是否清空？',
				confirmText: '清空',
				cancelText: '取消',
				confirm: () => {
					let products = []
					item.forEach(item => {
						products.push(
							{
								"itemNo": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.itemNo,
								"tickStatus": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.tickStatus,
								"requestQty": item.mainCmmdtyInfo.mainCmmdtyDetailInfo.requestQty,
								"deleteFlag": "Y" 
							}
						)
					})

					//debugger
					let params = JSON.stringify(
						{
							"cartHeadInfo": {
								"opType": "1",
								"operationStoreCode": rootState.position.storeLocation,
								"tempCartId": "",
								"userFlag": "0",
								"operationChannel": "50",
								"operationTerminal": "06",
								"operationEquipment": "06"
							},
							"operationInfos": products
						}
					)
					
					updateCenterCartInfo ( params )
						.then((products) => {
							commit('updateCenterCarts', { products })
						});
				},
				cancel: ()=>{
					commit('showMask', false)
				}
			})
		}
		

		/**
		 * 小店商品去结算
		 */
		,settlement ({ commit, rootState }, type ) {
			commit('showMask', true)
			let params = {
				"app": "wap",
				"appVersion": "3.2.2",
				"determine": "0",
				"flag": type,
				"mdmCityCode": rootState.position.cityCode,
				"storeLocation": rootState.position.storeLocation,
				"poiId": rootState.position.poiId,
      			"areaId": rootState.position.areaId
			}
			
			settlementInfo ( params )
				.then((json) => {
					commit('showMask', false)
					if(json.code==1){
						if (json.data.errorInfos && json.data.errorInfos.length) {
							return AlertBox({type: 'mini', msg: json.data.errorInfos[0].errorMessage});
						}
						
						commit('updateInvalidItems', null);
						router.push('/cart2')
						//跳转
					}else{
						if (json.data.errorInfos && json.data.errorInfos.length) {
							commit('updateInvalidItems', json.data.errorInfos);
						}
						else {
							alert(json.msg);
						}
					}
				});
		}
		// 中心仓结算
		,settlementCenter ({ commit, rootState }, type ) {
			commit('showMask', true)
			let params = {
				data: JSON.stringify({
					"cartHeadInfo": {
						"cityCode": "025",
						"districtCode": "02501",
						"operationStoreCode": "910A",
						"isRiskCheck": "0",
						"userFlag": "0",
						"token": "d41d8cd98f00b204e9800998ecf8427e4078b723",
						"directFlag": "0",
						"provinceCode": "100",
						"operationChannel": "50",
						"operationTerminal": "06",
						"operationEquipment": "02"
					},
					"immediateBuyItems": [
						{
							"itemHeadInfo": {
								"itemNo": "1",
								"activityId": "",
								"activityType": "01"
							},
							"mainCmmdtyInfo": {
								"shopCode": "0000000000",
								"itemNo": "2",
								"cmmdtyCode": "000000000121359325",
								"cmmdtyQty": "1"
							}
						},
						{
							"itemHeadInfo": {
								"itemNo": "1",
								"activityId": "",
								"activityType": "01"
							},
							"mainCmmdtyInfo": {
								"shopCode": "0000000000",
								"itemNo": "2",
								"cmmdtyCode": "000000000121359319",
								"cmmdtyQty": "4"
							}
						}
					]
				})
			}
			
			settlementCenterInfo ( params )
				.then((json) => {
					commit('showMask', false)
					if(json.code==1){
						if (json.data.errorInfos && json.data.errorInfos.length) {
							return AlertBox({type: 'mini', msg: json.data.errorInfos[0].errorMessage});
						}

						router.push('/cart2/center/'+json.data.result.cart2No)
						//跳转
					}else{
						alert (json.msg)
					}
				});
		}

	},
	getters: {
    	// 小店购物车：给一小时达商品和生鲜预订商品分类，返回list对象
		sufreshCarts: (state, getters, rootState) => {
			//cartHeadInfo 价格信息 onehourCarts 一小时达商品， reservedCarts 生鲜预订商品
			let list = {
				cartHeadInfo: {},
				onehourCarts: [], 
				reservedCarts: [],
				noSales: [],
				onehourCartsNumber: 0,
				reservedCartsNumber: 0
			}, allcheck =  false, currentCheck, falseFlag=0
			if(rootState.sufreshCarts){
				list.cartHeadInfo = rootState.sufreshCarts.cartHeadInfo;
				let shops = rootState.sufreshCarts.shopInfos || [];
				shops.forEach((ov, oi)=>{
					if (ov.cmmdtyInfos && !ov.cmmdtyInfos.length) return
					ov.cmmdtyInfos.forEach((tv, ti)=>{
						// 无库存 无价格 不可售商品
						if(tv.cmmdtyStatus=='0' || parseInt(tv.inventoryQty)<=0 || parseFloat(tv.salesPrice)<=0){
							tv.noSales = true;
							return list.noSales.push(tv);
						}
						// 普通商品
						if(tv.salesType=='0' || !tv.salesType){
							list.onehourCarts.push(tv)
							// 获取勾选状态商品数量
							if(tv.tickStatus=='1'){
								list.onehourCartsNumber += parseInt(tv.cmmdtyQty)
							}
						}
						// 预订商品
						else if(tv.salesType=='1'){
							list.reservedCarts.push(tv)
							// 获取勾选状态商品数量
							if(tv.tickStatus=='1'){
								list.reservedCartsNumber += parseInt(tv.cmmdtyQty)
							}
						}
					})
				})
				return list
			}else{
				return list
			}
		}

		//中心仓购物车：按照c店分类
		,centerCarts: (state, getters, rootState) => {
			if(rootState.centerCarts){
				//debugger
				let cmmdtyInfos = rootState.centerCarts.cmmdtyInfos,
				//isSales 可售列表   noSales 不可售列表  tickNumber 结算数量
				carts = {
					'isSales':{}, 
					'noSales': [], 
					'cartHeadInfo': rootState.centerCarts.cartHeadInfo, 
					'tickNumber': 0
				} 

				// 判断暂不销售商品
				let errorInfos = rootState.centerCarts.errorInfos;
				errorInfos.forEach((ov, oi)=>{
					//debugger
					var actCmmd = cmmdtyInfos.filter( x=> x.cmmdtyHeadInfo.itemNo==ov.itemNo);
					if (actCmmd.length) {
						actCmmd = actCmmd[0]
						actCmmd.cmmdtyHeadInfo.error = true;
						// 活动未开始的状态
						if (ov.errorCode == 'CSC-32-0010') {
							actCmmd.notbegin = true;
						}
					}
				})


				// 判断满减活动商品
				let discountInfos = rootState.centerCarts.discountInfos;
				console.log(cmmdtyInfos,1)
				
				discountInfos.forEach((ov, oi)=>{
					ov.cmmdtyLineInfos.forEach((tv, ti)=>{
						//debugger
						var actCmmd = cmmdtyInfos.filter( x=> x.cmmdtyHeadInfo.itemNo==tv.itemNo)
						if(!actCmmd.length) {return}
						actCmmd = actCmmd[0];
						actCmmd.cmmdtyHeadInfo.promotionId = ov.discountDetailInfo.promotionId
						actCmmd.cmmdtyHeadInfo.promotionDesc = ov.discountDetailInfo.promotionDesc
						actCmmd.cmmdtyHeadInfo.promotionType = ov.discountDetailInfo.promotionType
						actCmmd.cmmdtyHeadInfo.promSubType = ov.discountDetailInfo.promSubType
						actCmmd.cmmdtyHeadInfo.showFlag = ov.discountDetailInfo.showFlag
						actCmmd.cmmdtyHeadInfo.satisfiedFlag = ov.discountDetailInfo.satisfiedFlag
						actCmmd.cmmdtyHeadInfo.distanceValue = ov.discountDetailInfo.distanceValue
						// 数量单位
						switch(ov.discountDetailInfo.promSubType) {
							case '0': actCmmd.cmmdtyHeadInfo.unit = '件'; break;
							case '2': actCmmd.cmmdtyHeadInfo.unit = '元'; break;
						}
					})
				})
				
				console.log(cmmdtyInfos,2)

				// 给商品按照店铺 活动分类
				cmmdtyInfos.forEach((tv, ti)=>{
					if(!tv.cmmdtyHeadInfo.promotionId){
						tv.cmmdtyHeadInfo.promotionId = 'default'
					}

					let info = tv.mainCmmdtyInfo.mainCmmdtyDetailInfo

					// 判断商品是否可售，可售商品放入isSales对象 不可售商品放入noSales对象中
					/**
					 * isSales = {
					 * 		店铺编码: {
					 * 			list: {
					 * 				活动编码:[]
					 * 			}
					 * 			name: '店铺名称'
					 *		 }
					 * }
					 */
					if(info.cmmdtyStatus=='1'&&parseFloat(info.arrivalQty) > 0&&!tv.cmmdtyHeadInfo.error){
						// 有库存且可售商品 给商品按照店铺编码分类
						if(!carts.isSales[info.shopCode]){

							carts.isSales[info.shopCode] = {'name': '', 'list':{}}

							carts.isSales[info.shopCode].name = info.shopName;
							carts.isSales[info.shopCode].shopType = info.shopType;

							if(!carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId]){
								carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId] = [tv];
							}else{
								carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId].push(tv)
							}
							 
						}else{
							if(!carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId]){
								carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId] = [tv];
							}else{
								carts.isSales[info.shopCode].list[tv.cmmdtyHeadInfo.promotionId].push(tv)
							}
							//carts.isSales[info.shopCode].list.push(tv)
						}
						// 获取勾选状态商品数量
						if(info.tickStatus=='1'){
							carts.tickNumber += parseInt(info.cmmdtyQty)
						}
					}else{
						// 无货不可售商品
						tv.noSales = true
						carts.noSales.push(tv)
					}
				})

				//debugger
				

				return carts
			}
		}
	}
}

